package com.sea.wechat.filter;

import com.sea.wechat.util.AccessTokenUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * Servlet Filter implementation class WeChatFilter
 */
@WebFilter(description = "过滤器(获取token)", urlPatterns = { "/*" })
public class WeChatFilter implements Filter {

	private static Logger logger = LoggerFactory.getLogger(WeChatFilter.class);
    /**
     * Default constructor. 
     */
    public WeChatFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		//根据请求地址过滤不需要获取token的请求
		HttpServletRequest req = (HttpServletRequest) request;
		String path = req.getRequestURI();
		logger.info("=====>>>请求地址："+path);
		boolean isFilter = false;
		for (String filterPath : FilterData.filterData) {
			Pattern pattern = Pattern.compile(filterPath);
			Matcher m = pattern.matcher(path);
			if(m.find()) {
				isFilter = true;
               break ;
            }
		}
		if(isFilter){
			logger.info("=====>>>不需要拦截");
			chain.doFilter(request, response);
		}else {
			//获取token
			AccessTokenUtil.getToken();
			chain.doFilter(request, response);
		}
		
	}
	
	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
	}

}
